package com.security.customer.mobile;

import com.security.customer.CustomerUserDetailService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @Author: TongRui乀
 * @Date: 2020-04-03 14:42
 * @description： 使用短信验证码登陆的认证器
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private CustomerUserDetailService customerUserDetailService;

    public SmsCodeAuthenticationProvider (CustomerUserDetailService customerUserDetailService){
        this.customerUserDetailService = customerUserDetailService;
    }

    public SmsCodeAuthenticationProvider(){}


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        SmsCodeAuthenticationToken token = (SmsCodeAuthenticationToken) authentication;

        UserDetails userDetails = this.customerUserDetailService.loadUserByUsername((String) token.getPrincipal());

        if(userDetails == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities());

        authenticationResult.setDetails(token.getDetails());

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }

    public CustomerUserDetailService getCustomerUserDetailService() {
        return customerUserDetailService;
    }

    public void setCustomerUserDetailService(CustomerUserDetailService customerUserDetailService) {
        this.customerUserDetailService = customerUserDetailService;
    }
}
